﻿using IIControls.IAControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace Communicate
{
  public   class AgreePrivateByTcp 
    {


        /// <summary>
        /// <para>该类用法</para>
        /// <para>1、传入SendByTcp.InitData参数，该参数是TCP服务器的配置信息</para>
        /// <para>2、调用delegateinit进行初始化委托</para>
        /// <para>3、调用SocketStart开始服务</para>
        /// <para>4、调用ADDTasks、DELTaskMsg修改任务，在任务已经开始运行后允许新增任务，已经运行过的任务不允许删除</para>
        /// <para>5、调用TasksStart开始任务</para>
        /// </summary>
        /// <param name="data">初始化TCP的数据格式</param>
        /// <param name="ReceiveData">委托用于通知主方法收到了数据</param>
        public AgreePrivateByTcp (SendByTcp.InitData data, TCPReceiveData ReceiveData)
        {
            AgreePrivateByTcpInit(data, ReceiveData);
        }

        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="data"></param>
        /// <param name="ReceiveData"></param>
        private void AgreePrivateByTcpInit(SendByTcp.InitData data, TCPReceiveData ReceiveData)
        {
            if (IsCorrectIP(data.ip) && data.port == 0 && data.register == null && data.heartbeat == null)
                throw new Exception("0");  //抛出0代表参数错误
            SocketInfo = data;
            SBT = new SendByTcp();
            SendByTcp.ReceiveSocketData RS = new Communicate.SendByTcp.ReceiveSocketData(ReceiveBytes);
            delegateinit(RS);
            TCPData = ReceiveData;
        }




        /// <summary>
        /// TCP服务器基本信息
        /// </summary>
        public SendByTcp.InitData SocketInfo { get; set; }

        /// <summary>
        /// 处理协议
        /// </summary>
        public AgreePrivate AP;

        /// <summary>
        /// 回掉方法，用于处理收到的数据
        /// </summary>
        /// <param name="RS"></param>
        public void delegateinit(SendByTcp.ReceiveSocketData RS)
        {
            SBT.delegateinit(RS);
            AgreePrivate.del_Send SendMsg = new Communicate.AgreePrivate.del_Send(SendBytes);
            AP = new Communicate.AgreePrivate(SendMsg, "20993001", 2);
        }


        TCPReceiveData TCPData;
       public  delegate void TCPReceiveData(byte[] data,string data2string);

        /// <summary>
        /// 收到数据处理
        /// </summary>
        /// <param name="data"></param>
        private void ReceiveBytes(byte[] data)
        {
            List<byte[]> bytes = new List<byte[]>();
            bytes = GetJson(data);  //粘包处理
            for (int i=0;i<bytes.Count;i++)
            {
                //try
                //{
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string recstring = System.Text.Encoding.Default.GetString(bytes[i]);
                    Dictionary<string, object> listres = js.Deserialize<Dictionary<string, object>>(recstring);
                    if (listres.Keys.Contains("device_type") && listres.Keys.Contains("device_cmd") && listres.Keys.Contains("device_code") && listres.Keys.Contains("gprs_code"))
                    {
                        if (Convert.ToInt32(listres["device_type"]) == 10 && Convert.ToInt32(listres["device_cmd"]) == 1)
                        {
                            AP.locks = 1;  //打包数据发送成功
                        if (AP.TaskPackage.Count > 0)
                        {
                            AP.clearstatue(AP.TaskPackage[0].ToArray());
                            AP.TaskPackage.RemoveAt(0);
                        }
                        }
                        else if (Convert.ToInt32(listres["device_type"]) == 10 && Convert.ToInt32(listres["device_cmd"]) == 6)
                            respondServer(listres);  //全部操作成功
                        else if (Convert.ToInt32(listres["device_type"]) == 10 && Convert.ToInt32(listres["device_cmd"]) == 2)
                            respondServer(listres); //失败数据打包
                    
                }
                RecData.ReceiveDataAnaly(bytes[i], recstring);
                TCPData(bytes[i], recstring);
                //}
                //catch (Exception ex)
                //{
                //    //json反序列化失败就什么也不做

                //}

            }
        }

        /// <summary>
        /// 清除已按下标识
        /// </summary>
        /// <param name="TM"></param>
        private void ClearStatue(TaskMsg[] TM)
        {
            foreach (TaskMsg item in TM )
            {

            }
        }



        private void respondServer(Dictionary<string,object > D)
        {
            string  GPRSCode = D["gprs_code"].ToString();
            byte types = Convert.ToByte(D["device_type"]);
            byte oper= Convert.ToByte(D["device_cmd"]);
            int[] ids = new int[] { Convert.ToInt32(D["device_code"].ToString().Substring(2, D["device_code"].ToString().Length - 2)) };
            AP.sendImmediatelyTask(GPRSCode, types, oper, ids, null);
        }

        /// <summary>
        /// 收到byte[]中，把{}中的数据变成list<byte[]>中一项
        /// </summary>
        /// <param name="reg">收到的数组</param>
        /// <returns></returns>
        private List<byte[]> GetJson(byte[] reg)
        {
            List<byte[]> ReadJson = new List<byte[]>();
            ReadJson= JsonSpliter.Spliter.IsJsons(reg);
            return ReadJson;
        }



        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        private void SendBytes(byte[] data)
        {
            SBT.Send(data);
        }

        /// <summary>
        /// 使用TCP协议发送数据
        /// </summary>
        SendByTcp SBT;

        /// <summary>
        /// 判断字符串是否是ip地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
         bool IsCorrectIP(string ip)
        {
            if (ip == null)
                return false;
            Regex rx = new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
            return rx.IsMatch(ip);
        }

        /// <summary>
        /// 开启SOCKET服务
        /// </summary>
        public  bool  SocketStart()
        {
            SBT.TCPConfig(SocketInfo);
            return   SBT.TCPStart();
        }

        /// <summary>
        /// 停止TCP服务
        /// </summary>
        public void SocketStop()
        {
            SBT.dispose();
        }

        /// <summary>
        /// 增加一个任务
        /// </summary>
        /// <param name="tasks"></param>
        public void ADDTasks(TaskMsg tasks)
        {

            AP.ADDTaskMsg(tasks);
        }
        /// <summary>
        /// 删除一个任务
        /// </summary>
        /// <param name="tasks"></param>
        public void DELTasks(TaskMsg tasks)
        {
            AP.DELTaskMsg(tasks);
        }

        /// <summary>
        /// 开始执行任务
        /// </summary>
        public void TasksStart()
        {
            AP.SendTasks();
        }

        /// <summary>
        /// 移除所有任务
        /// </summary>
        public bool RemoveAllTask()
        {
            return AP.RemoveAllMsg();
        }

    }
}
